package com.example.myandroidtest.ui.component.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.IBinder;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.example.myandroidtest.R;

public class MusicServiceOld extends Service {
    // 通知通道与通知 ID
    private static final String CHANNEL_ID = "music_play_channel";
    private static final int NOTIF_ID = 1001;

    // 通知动作字符串，用于区分点击事件
    private static final String ACTION_PLAY = "ACTION_PLAY";
    private static final String ACTION_PAUSE = "ACTION_PAUSE";
    private static final String ACTION_STOP = "ACTION_STOP";

    private MediaPlayer mediaPlayer;
    private boolean isPlaying = false;

    @Override
    public void onCreate() {
        super.onCreate();
        // 1. 创建通知渠道（Android 8.0+）
        createNotificationChannel();
        // 2. 初始化 MediaPlayer
        initMediaPlayer();
    }

    /**
     * 在 startService/startForegroundService 后回调
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 区分点击通知的 Action
        if (intent != null && intent.getAction() != null) {
            switch (intent.getAction()) {
                case ACTION_PLAY:
                    resumeMusic();
                    break;
                case ACTION_PAUSE:
                    pauseMusic();
                    break;
                case ACTION_STOP:
                    stopSelf(); // 停止 Service
                    return START_NOT_STICKY;
            }
        } else {
            // 首次启动，直接开始播放
            startMusic();
        }

        // 每次 onStartCommand 都需要调用 startForeground，保持前台状态
        startForeground(NOTIF_ID, buildNotification());
        // 如果被系统杀掉，不再自动重启
        return START_NOT_STICKY;
    }

    /**
     * 初始化 MediaPlayer，并设置音频属性
     */
    private void initMediaPlayer() {
        mediaPlayer = MediaPlayer.create(this, R.raw.sample_music);
        mediaPlayer.setLooping(true); // 循环播放
        // 适配 API21+ 的音频属性
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mediaPlayer.setAudioAttributes(new AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).setUsage(AudioAttributes.USAGE_MEDIA).build());
        } else {
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        }
    }

    /**
     * 开始播放并更新状态
     */
    private void startMusic() {
        if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
            mediaPlayer.start();
            isPlaying = true;
        }
    }

    /**
     * 暂停播放并更新状态
     */
    private void pauseMusic() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            isPlaying = false;
        }
    }

    /**
     * 恢复播放并更新状态
     */
    private void resumeMusic() {
        if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
            mediaPlayer.start();
            isPlaying = true;
        }
    }

    /**
     * 构建前台服务通知，包含播放/暂停/停止按钮
     */
    private Notification buildNotification() {
        // 点击通知主体，返回 MainActivity
        PendingIntent mainIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                MusicActivity.class),
                PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

        // 播放/暂停按钮 Intent
        Intent playPauseIntent = new Intent(this, MusicServiceOld.class).setAction(isPlaying ?
                ACTION_PAUSE : ACTION_PLAY);
        PendingIntent ppPending = PendingIntent.getService(this, 1, playPauseIntent,
                PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

        // 停止按钮 Intent
        Intent stopIntent = new Intent(this, MusicServiceOld.class).setAction(ACTION_STOP);
        PendingIntent stopPending = PendingIntent.getService(this, 2, stopIntent,
                PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

        // 构造 Notification
        NotificationCompat.Builder builder =
                new NotificationCompat.Builder(this, CHANNEL_ID).setContentTitle("正在播放音乐").setContentText(isPlaying ? "点击暂停" : "点击播放").setSmallIcon(R.drawable.ic_music_note).setContentIntent(mainIntent) // 点击通知主体
                .addAction(isPlaying ? R.drawable.ic_pause : R.drawable.ic_play, isPlaying ?
                        "暂停" : "播放", ppPending).addAction(R.drawable.ic_stop, "停止", stopPending);
//        setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
//        .setShowActionsInCompactView(0, 1))
        // 使用 MediaStyle，支持在锁屏及车载展示
        return builder.build();
    }

    /**
     * 创建通知渠道（Android 8.0+）
     */
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel chan = new NotificationChannel(CHANNEL_ID, "音乐播放服务",
                    NotificationManager.IMPORTANCE_LOW);
            chan.setDescription("用于在后台播放音乐的前台服务");
            NotificationManager mgr = getSystemService(NotificationManager.class);
            if (mgr != null) {
                mgr.createNotificationChannel(chan);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 释放 MediaPlayer
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        // 取消前台状态与通知
        stopForeground(true);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        // 不提供绑定，此处返回 null
        return null;
    }
}
